from flask import Flask, render_template, request, redirect, url_for, session
import mysql.connector
import fitness_system_detect_detection.videoprocess as vp
import fitness_system_detect_detection.trainingsetprocess as tp
import fitness_system_detect_detection.videocapture as vc

app = Flask(__name__, static_folder='static')

# Configure database connection information
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'text'

# Set session secret key
app.secret_key = 'secret_key'

# Connect to the database
mysql = mysql.connector.connect(
    host=app.config['MYSQL_HOST'],
    user=app.config['MYSQL_USER'],
    password=app.config['MYSQL_PASSWORD'],
    database=app.config['MYSQL_DB']
)

class User:
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __repr__(self):
        return f'<User {self.username}>'

@app.route('/')
def to_login():
    # Redirect to the login page
    return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        cur = mysql.cursor()

        # Query user information from the database
        cur.execute("SELECT * FROM users WHERE username = %s", (username,))
        user = cur.fetchone()
        cur.close()

        # Validate user information
        if user is None or user[2] != password:
            error = '密码或用户名错误'
            return render_template('login.html', error=error)
        else:
            # Store the username in the session
            session['username'] = user[1]
            return redirect(url_for('index'))

    # Display the login page template
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        cur = mysql.cursor()

        # Insert new user into the database
        cur.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
        mysql.commit()
        cur.close()

        # Redirect to the login page after successful registration
        return redirect(url_for('login'))

    # Display the registration page template
    return render_template('register.html')

@app.route('/logout')
def logout():
    # Clear the username information from the session
    session.pop('username', None)

    # Redirect to the login page after logging out
    return redirect(url_for('login'))

@app.route('/index', methods=['GET', 'POST'])
def index():
    if 'username' in session:
        if request.method == 'POST':
            mode = int(request.form['mode'])
            exercise = int(request.form['exercise'])
            if mode == 1:
                flag = exercise
                video = request.files['file']
                video_path = 'uploads/' + video.filename
                video.save(video_path)
                tp.trainset_process(flag)
                result = vp.video_process(video_path, flag)  # Assuming vp.video_process() returns some result
                last_frame_path = 'static/last_frame.jpg'  # Assuming you save the last frame as 'last_frame.jpg'
                return render_template('result.html', result=result, last_frame=last_frame_path)
            elif mode == 2:
                flag = exercise
                tp.trainset_process(flag)
                result = vc.process(flag)  # Assuming vc.process() returns some result
                if result:
                    last_frame_path = 'static/last_frame.jpg'  # Assuming you save the last frame as 'last_frame.jpg'
                    return render_template('result.html', result=last_frame_path, last_frame=last_frame_path)
                else:
                    return '视频处理失败，请重试！'
            else:
                return '无效的模式'
        else:
            return render_template('index.html', username=session['username'])
    else:
        return redirect(url_for('login'))



@app.route('/exit')
def exit():
    return render_template('exit.html')

if __name__ == '__main__':
    # Start the Flask application in debug mode
    app.run(debug=True)
